package com.example.demo54acl.controller;

import com.example.demo54acl.domain.NoticeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.acls.domain.BasePermission;
import org.springframework.security.acls.domain.ObjectIdentityImpl;
import org.springframework.security.acls.domain.PrincipalSid;
import org.springframework.security.acls.jdbc.BasicLookupStrategy;
import org.springframework.security.acls.jdbc.JdbcMutableAclService;
import org.springframework.security.acls.model.MutableAcl;
import org.springframework.security.acls.model.ObjectIdentity;
import org.springframework.security.acls.model.Permission;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class HelloController {

    @Autowired
    JdbcMutableAclService jdbcMutableAclService;

    /**
     * 1.首先分别创建 ObjectIdentity 和 Permission 对象，然后创建一个 acl 对象出来
     * 2.接下来调用 acl_insertAce 方法，将 ace 存入 acl 中(此时 ace 还没有存储数据库)，最后调用 updateAcl 方法去更新 acl 对象即可
     */
    @GetMapping("/hello1")
    @Transactional
    public String hello1(){
        ObjectIdentity objectIdentity = new ObjectIdentityImpl(NoticeMessage.class, 1);
        Permission p = BasePermission.READ;
        MutableAcl acl = jdbcMutableAclService.createAcl(objectIdentity);
        acl.insertAce(acl.getEntries().size(), p, new PrincipalSid("wangnian"), true);
        jdbcMutableAclService.updateAcl(acl);
        return "hello1";
    }

    /**
     * 注意这里权限改为 WRITE 权限。由于 acl 中已经存在这个 ObjectIdentity 了，所以这里通过 readAclById 方法直接读取已有的 acl 即可
     */
    @GetMapping("/hello2")
    @Transactional
    public String hello2(){
        ObjectIdentity objectIdentity = new ObjectIdentityImpl(NoticeMessage.class, 1);
        Permission p = BasePermission.WRITE;
        MutableAcl acl = (MutableAcl) jdbcMutableAclService.readAclById(objectIdentity);
        acl.insertAce(acl.getEntries().size(),p,new PrincipalSid("wangnian"),true);
        jdbcMutableAclService.updateAcl(acl);
        return "hello2";
    }

    /**
     * 对 wangnian 赋予 id 为 99 的 NoticeMessage 的 CREATE 和 READ 的权限
     */
    @GetMapping("/hello3")
    @Transactional
    public String hello3(){
        ObjectIdentity objectIdentity = new ObjectIdentityImpl(NoticeMessage.class, 99);
        Permission p = BasePermission.CREATE;
        Permission p2 = BasePermission.READ;
        MutableAcl acl = jdbcMutableAclService.createAcl(objectIdentity);
        acl.insertAce(acl.getEntries().size(),p,new PrincipalSid("wangnian"),true);
        acl.insertAce(acl.getEntries().size(),p2,new PrincipalSid("wangnian"),true);
        jdbcMutableAclService.updateAcl(acl);
        return "hello3";
    }


}
